package com.example.loginProject.aop;

import com.example.loginProject.exception.ServiceException;
import com.example.loginProject.utils.TokenUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

//切面类
//1、如果实现AOp功能，添加aop依赖信息
@Aspect
@Component
public class logAspect {
    //所有的连接点称为连接点
    //切入点：部分连接点，根据切入规则
    @Pointcut("execution(* com.example.loginProject.controller.*.*(..)) && @annotation(Logging)")   //使用@Pointcut编写哪些方法需要日志
    public void LogCutPoint(){

    }

    @Before("LogCutPoint()")
    public void before(){   //通知，
        System.out.println("前置信息");
        //获取到浏览器访问系统的请求信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();

        String token = request.getHeader("Authorization");

        if(token==null){
            throw new ServiceException("用户未登录");
        }
        String username = TokenUtil.getUserId(token);
        Map<String, Object> map = TokenUtil.getInfo(token);

    }
    @After("LogCutPoint()")
    public  void after(){
        System.out.println("后置通知");
    }
    @Around("LogCutPoint()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("开始环绕通知");
        Object object = pjp.proceed();
        System.out.println("结束环绕通知");
        return object;
    }
}
